import { getOpenid, loginSys } from '../config/login'
import {SUCCESS_CODE} from './constants'

const constants = require('./constants')

export const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

export const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

export const myAjax = function ({
  baseUrl = constants.API_ROOT_URL,
  url,
  data = {},
  method = 'post',
  showLoading = true,
  changeToJSON = false,
  showFailMessage = false // 是否在不是成功状态下展示错误信息， false toast: 使用toast展示 modal 使用模态框展示错误
}) {
  if (showLoading) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
  }
  // 是否转换为包裹形式
  let fdata = changeToJSON ? { params: JSON.stringify(data) } : data
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      data: fdata,
      method: method,
      timeout: 180 * 1000,
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: res => {
        setTimeout(async () => {
          console.log(res)
          if (res.statusCode === 200) {
            if (res.data.code === constants.INVALID_TOKEN) {
              await showModalTip('登录失效，请重新登录')
              wx.removeStorageSync('token')
              wxLogin()
              return
            }
            if (!showFailMessage) {
              resolve(res.data)
            } else {
              if (res.data.code !== constants.SUCCESS_CODE) {
                const msg = res.data.message || '请求出错'
                showFailMessage === 'modal' ? showModalTip(msg) : showErrorToast(msg)
                reject(res.data.message)
                return
              }
              resolve(res.data)
              return
            }
          }  else {
            const msg = `${res.statusCode}，请求出错`
            showErrorToast(msg)
            reject(msg)
          }
        })
      },
      fail: err => {
        console.log('failed', err)
        setTimeout(() => {
          reject(err)
          wx.showToast({
            title: '请检查网络',
            icon: 'error',
            duration: 5000
          })
        })
      },
      complete: () => {
        if (showLoading) {
          wx.hideLoading()
        }
      }
    })
  })
}

export const validPhone = phone => {
  return /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(phone)
}

/**
 * 获取最新版本
 */ 
export const updateVerson = () => {
  const updateManager = wx.getUpdateManager()

    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      if (res.hasUpdate) {
        updateManager.onUpdateReady(function () {
          setTimeout(() => {
            updateManager.applyUpdate()
          })
          // wx.showModal({
          //   title: '更新提示',
          //   content: '新版本已经准备好，是否重启应用？',
          //   success: function (res) {
          //     if (res.confirm) {
          //       // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                
          //     }
          //   }
          // })
        })
      }
    })
}

/**
 * 调用微信登录
 */
export const login = () => {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          resolve(res.code);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}
/**
 * 登录
 */
export const wxLogin = async () => {
  const code = await login()
  const { res } = await awaitWrap(getOpenid(code))
  if (res?.code === constants.SUCCESS_CODE) {
    const data = res.data || {}
    const app = getApp()
    app.globalData.openid = data.openId || ''
    if (data.phone) {
      // 登录公司系统
      const params = {
        phone: data.phone,
        openid: data.openId,
        way: 2 // 1 手机号登录，2微信授权登录
      }
      // 避免登录接口将全局loading关闭
      setTimeout(async () => {
        const { res } = await awaitWrap(loginSys(params, { showLoading: true }))
        if (res?.code === SUCCESS_CODE) {
          const loginData = res.data || {}
          setGlobalInfo(loginData)
        }
      }, 10)
    } else {
      // wx.navigateTo({
      //   url: '/pages/login/index',
      // })
    }
  }
}
// 设置全局参数
export const setGlobalInfo = (data) => {
  return new Promise(resolve => {
    wx.setStorageSync('token', data.ftoken || '')
    const app = getApp()
    const userInfo = {
      userId: data.fsysUserId,
      name: data.frealName,
      phone: data.fphone,
      region: data.fregion
    }
    app.globalData.userBaseInfo = userInfo
    wx.setStorageSync(app.globalData.storageKey, userInfo)
    if (app.loginCallback) {
      typeof app.loginCallback == 'function' && app.loginCallback()
    }
  })
}
/**
 * 报错
 */
export const showErrorToast = (msg) => {
  setTimeout(() => {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 5000
    })
  }, 200)
}

// 确认弹窗
export const showConfirm = (options = {
  title: '提示',
  content,
  confirmColor: '#00A585'
}) => {
  return new Promise((resolve, reject) => {
    wx.showModal({
      ...options,
      success (res) {
        if (res.confirm) {
          return resolve()
        }
        reject()
      }
    })
  })
}

/**
 * 报带有确认按钮的错误
*/
export const showModalTip = (msg) => {
  return new Promise(resolve => {
    wx.showModal({
      title: '提示',
      content: msg,
      showCancel: false,
      success (res) {
        resolve()
      }
    })
  })
}

// 其他证件校验
export const validateOtherIdCard = function (val) {
  return /^[0-9A-Za-z-_]{6,}$/.test(val)
}

//  身份证校验
export const identityNumberValid = code => {
  let city = {
    11: '北京',
    12: '天津',
    13: '河北',
    14: '山西',
    15: '内蒙古',
    21: '辽宁',
    22: '吉林',
    23: '黑龙江',
    31: '上海',
    32: '江苏',
    33: '浙江',
    34: '安徽',
    35: '福建',
    36: '江西',
    37: '山东',
    41: '河南',
    42: '湖北',
    43: '湖南',
    44: '广东',
    45: '广西',
    46: '海南',
    50: '重庆',
    51: '四川',
    52: '贵州',
    53: '云南',
    54: '西藏',
    61: '陕西',
    62: '甘肃',
    63: '青海',
    64: '宁夏',
    65: '新疆',
    71: '台湾',
    81: '香港',
    82: '澳门',
    91: '国外 '
  }
  let tip = ''
  let pass = true

  if (!code || !/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/i.test(code)) {
    tip = '身份证号格式错误'
    pass = false
  } else if (!city[code.substr(0, 2)]) {
    tip = '地址编码错误'
    pass = false
  } else {
    // 18位身份证需要验证最后一位校验位
    if (code.length === 18) {
      // ∑(ai×Wi)(mod 11)
      // 加权因子
      let factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ]
      // 校验位
      let parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ]
      let sum = 0
      let ai = 0
      let wi = 0
      for (let i = 0; i < 17; i++) {
        ai = code[i]
        wi = factor[i]
        sum += ai * wi
      }
      let last = parity[sum % 11] + ''
      if (last !== code[17]) {
        tip = '校验位错误'
        pass = false
      }
    }
  }
  return {
    pass: pass,
    message: tip
  }
}

// 计算年龄
export const getAge = (birthday) => {
  if (!birthday) return 0
  let time = new Date(birthday).getTime()
  let nowTime = new Date().getTime()
  return Math.ceil((nowTime - time) / (365 * 24 * 60 * 60 * 1000))
}

export const awaitWrap = (promise) => {
  return promise
    .then(data => {
      return { err: null, res: data }
    })
    .catch(err => {
      return { err, res: null }
    })
}

export const scanCode = () => {
  return new Promise(resolve => {
    wx.scanCode({
      success: (res) => {
        const { rawData, result } = res
        resolve({
          base64: rawData,
          str: result
        })
      },
      fail: () => {
        showErrorToast('调用扫码失败')
      }
    })
  })
}

export const strToBinary = (str) => {
  var result = [];
  var list = str.split("");
  for(var i=0;i<list.length;i++){
      if(i != 0){
          result.push(" ");
      }
      var item = list[i];
      var binaryStr = item.charCodeAt().toString(2);
      result.push(binaryStr);
  }   
  return result.join("");
}

/**
 * 深拷贝
 * **/
export const deepCopy = (obj) => {
  return JSON.parse(JSON.stringify(obj))
}

/**
 * 检查网络
 * **/
export const checkNetworkType = () => {
  return new Promise(resolve => {
    wx.getNetworkType().then(res => {
      console.log(res)
      resolve(res.networkType !== 'none')
    }).catch(() => {
      showModalTip('检查网络失败')
    })
  })
}
